<template>
  <div id="app" />
</template>

<script>
import Stomp from 'stompjs'

// const MQTT_SERVICE = process.env.VUE_APP_MQ_API // mqtt服务地址
const MQTT_USERNAME = 'admin' // mqtt连接用户名
const MQTT_PASSWORD = '123456' // mqtt连接密码
export default {
  name: 'App',
  data() {
    return {
      client: Stomp.client('ws://127.0.0.1:15674/ws')
    }
  },
  mounted() {
    console.log('初始化中')
    this.connect()
  },
  methods: {
    onConnected: function(frame) {
      // 订阅频道，如果有交换机写'/exchange/交换机名/key名'
      // 如果没有交换机则写'queue名/key名'
      console.log('连接到stomp')
      const topic = '/queue/firstQueue'
      this.client.subscribe(topic, this.responseCallback, this.onFailed)
    },

    onFailed: function(frame) {
      console.log('MQ Failed: ' + frame)
    },

    responseCallback: function(frame) {
      // 接收消息处理
      var jsonObject = JSON.parse(frame.body)
      jsonObject.forEach(res => {
        if (res.id === 30) {
          alert(res.name)
        }
      })
    },

    connect: function() {
      console.log('准备进行链接')
      // 初始化mqtt客户端，并连接mqtt服务
      const headers = {
        login: MQTT_USERNAME,
        passcode: MQTT_PASSWORD
      }
      this.client.connect(headers, this.onConnected, this.onFailed)
    }
  }
}
</script>
